#!/usr/bin/perl
use strict;

# load config
if(-f "$ENV{HOME}/.bictransfer") {
	{ package Settings; do "$ENV{HOME}/.bictransfer" }
}
if (!defined %Settings::db) {
    print "\n\tERROR: Config file error - could not load config settings\n\n"; exit 33;
} 

my ($studyDir,$libraryDir) = @ARGV;

if(!-e $studyDir || !-e $libraryDir || !-w $libraryDir) {
	print "Usage: $0 <study dir> <library root dir>\n";
	exit(1);
}

# determine the study date
my $studyDate = `find $studyDir -type f | head -1 | /usr/local/dicomSummary/get_dicom_info.pl -date -stdin`;
my $studyYear = substr($studyDate, 0, 4);

# create the target dir if it does not exist
my $destDir = $libraryDir.'/'.$studyYear;
if(!-e $destDir) {
	if(!mkdir($destDir, 0755)) {
		print "Could not create destination dir $destDir\n";
		exit(2);
	}
}

# tarchive into the target dir
my @cmd = ("/usr/local/dicomSummary/dicomTar.pl", "-centerName", $Settings::centerName, "-database", "-profile", $Settings::profileName, "-clobber", "-noverbose", $studyDir, $destDir);
if(system(@cmd) != 0) {
	open LIST, ">>$ENV{'HOME'}/pendingDicomTar.list";
	print LIST $studyDir."\n";
	close LIST;

	open MAIL, "|Mail -s 'URGENT dicomTar failed at $Settings::centerName!' $Settings::contactEmail";
	print MAIL "`hostname`\n";
	print MAIL "$studyDir\n";
	print MAIL "Could not be Tarchived\n";
	close MAIL;

	exit(3);
}

# fixme: now update the tarchive database to reset the date sent and
# pending transfer to make sure that a retransfer of previously sent
# data does not trigger a new transfer automatically.


exit(0);
